package com.example.iterceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class HandleInterceptor implements HandlerInterceptor {
    @Override//预处理: 在controller方法执行前执行, 返回值为true时放行, false时拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("Authorization");
        log.info("token: {}", token);
        //4.判断token是否为空，如果为空表示未登录，返回未登录信息(json)
        if(token==null || token.isEmpty()){
            Result error = Result.error("token不能为空");
            System.out.println(error);
            String json = JSONObject.toJSONString(error);
            resp.getWriter().write(json);
            return false;
        }
        //5.解析token，如果解析失败表示登录信息已经过期，返回未登录信息(json)
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("登录信息过期");
            String json =JSONObject.toJSONString(error);
            resp.getWriter().write(json);
            return false;
        }
        //6.放行
        log.info("验证成功，放行");
       return true;
    }


    @Override//后处理: 在controller方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override//释放资源: 在controller方法执行后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
